package com.vecspace.utils;

import java.util.Iterator;

import org.dom4j.Element;
import org.dom4j.Node;

/**dom4j辅助类
 * 
 * @version: 1.0
 * @author: wanghua
 */
public class XmlUtils {
	/**
	 * 根据父节点和子节点名称，获取子节点（不递归）
	 * @param element
	 * @param childNodeName
	 * @return 
	 * @author: wanghua
	 */
	public static Element getChildElement(Element element, String childNodeName){
		if(element == null) {
			return null;
		}
		if(childNodeName == null || childNodeName.length() == 0){
			return null;
		}
		Iterator<?> elementIterator = element.elementIterator();
		while(elementIterator.hasNext()){
			Element element2 = (Element)elementIterator.next();
			String name2 = element2.getName();
			if(childNodeName.equals(name2)){
				return element2;
			}
		}
		return null;
	}
	/**读取节点element下一级子节点childNodeName的InnerText
	 * @param element
	 * @param childNodeName
	 * @return 
	 * @author: wanghua
	 */
	public static String readChildInnerText(Element element, String childNodeName){
		if(element == null) {
			return null;
		}
		if(childNodeName == null || childNodeName.length() == 0){
			String text = element.getText();
			return text;
		}
		Iterator<?> elementIterator = element.elementIterator();
		while(elementIterator.hasNext()){
			Element element2 = (Element)elementIterator.next();
			String name2 = element2.getName();
			if(childNodeName.equals(name2)){
				String text = element2.getText();
				return text;
			}
		}
		return null;
	}
	
	/**
	 * 读取节点node子节点childNodeName的InnerText
	 * @param node
	 * @param childNodeName
	 * @return 
	 * @author wanghua
	 */
	public static String readChildInnerText(Node node, String childNodeName) {
		if(node == null) {
			return null;
		}
		if(childNodeName == null || childNodeName.length() == 0){
			String text = node.getText();
			return text;
		}
		Node childNode = node.selectSingleNode(childNodeName);
		if(childNode != null) {
			String text = childNode.getText();
			return text;
		}
		return null;
	}

	/**
	 * 读取节点node子节点childNodeName的属性名为attrName的属性值
	 * @param node
	 * @param childNodeName
	 * @return
	 * @author wanghua
	 */
	public static String readChildAttrValue(Node node, String childNodeName, String attrName) {
		if(node == null) {
			return null;
		}
		Node childNode = node.selectSingleNode(childNodeName);
		if(childNode != null) {
			Element element = (Element)childNode;
			String val = element.attributeValue(attrName);
			return val;
		}
		return null;
	}
}
